package test.cycledetect;

import java.util.HashSet;
import java.util.Set;

/**
 * Definition for singly-linked list.
 * class ListNode {
 * int val;
 * ListNode next;
 * ListNode(int x) {
 * val = x;
 * next = null;
 * }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {

        if (head == null) {
            return null;
        }

        Set<ListNode> set = new HashSet<>();
        ListNode cur = head;
        while (!set.contains(cur.next)) {
            set.add(cur);
            cur = cur.next;
            if (cur == null) {
                return null;
            }
        }
        return cur.next;
    }

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}